package com.example.delicioushunter.control.databasecontrol;

import java.util.ArrayList;

import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;

import com.example.delicioushunter.control.supportcontrol.BitmapProcess;
import com.example.delicioushunter.model.database.BookColumns;
import com.example.delicioushunter.model.database.MaterialColumns;
import com.example.delicioushunter.model.object.Material;

public class MaterialControl {
	private final static String MATERIALS_TABLE = "tbl_materials";

	public void addMaterial(ArrayList<Material> materials, SQLiteDatabase db) {
		BitmapProcess process = new BitmapProcess();
		for (Material m : materials) {
			ContentValues values = new ContentValues();
			values.put(MaterialColumns.NAME, m.getName());
			values.put(MaterialColumns.IMAGE, process.getBytes(m.getImage()));

			db.insert(MATERIALS_TABLE, null, values);
		}
		db.close();
		Log.d("Database", "Add materials");
	}

	public ArrayList<Material> getAllMaterials(SQLiteDatabase db) {
		ArrayList<Material> materials = new ArrayList<Material>();
		String selectQuery = "SELECT  * FROM " + MATERIALS_TABLE + " ORDER BY "
				+ MaterialColumns.NAME + " DESC";
		Cursor cursor = db.rawQuery(selectQuery, null);
		BitmapProcess process = new BitmapProcess();
		if (cursor.moveToFirst()) {
			do {
				Material m = new Material();
				m.set_id(Integer.parseInt(cursor.getString(0)));
				m.setName(cursor.getString(1));
				m.setImage(process.getImage(cursor.getBlob(2)));

				materials.add(m);
			} while (cursor.moveToNext());
		}
		db.close();
		Log.d("Database", "Get all materials");
		return materials;
	}

	public void deleteMaterial(int _id, SQLiteDatabase db) {
		db.delete(MATERIALS_TABLE, BookColumns.ID + " = ?",
				new String[] { String.valueOf(_id) });
		db.close();
	}
}
